package com.isoftstone.merchant.controller.role;


import com.isoftstone.bank.controller.base.BaseController;
import com.isoftstone.common.Page;
import com.isoftstone.common.Tidings;
import com.isoftstone.common.entity.SysMenu;
import com.isoftstone.common.entity.SysRole;
import com.isoftstone.common.entity.SysRoleMenu;
import com.isoftstone.common.entity.SysUser;
import com.isoftstone.common.service.*;
import com.isoftstone.common.service.impl.SysMenuService;
import com.isoftstone.util.Const;
import com.isoftstone.util.PageData;
import com.isoftstone.util.UuidUtil;
import com.isoftstone.util.XSSCheckUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import sun.plugin.util.UIUtil;

import java.net.URLDecoder;
import java.rmi.server.UID;
import java.util.*;

@Controller
public class SysRoleController extends BaseController {
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysUserRoleService sysUserRoleService;
    @Autowired
    ISysUserService sysUserService;
    @Autowired
    ISysRoleMenuService sysRoleMenuService;
    @Autowired
    SysMenuService sysMenuService;

        /**
         * 连接地址权限
         * @param page
         * @return
         */
        @RequiresPermissions("mms-menu.001.002")
        @RequestMapping("/merchant/role/getToRolelistPage")
        public ModelAndView getToRolelistPage(Page page) {
            ModelAndView md = new ModelAndView();
            md.setViewName("merchant/sys_management/role_manage");
            return md;
        }
        @RequestMapping("/merchant/role/getRolelistPage")
        @ResponseBody
        public Object getRolelistPage(Page page) {
            Tidings<List<SysRole>> tidings=new Tidings<List<SysRole>>();
            PageData pd = this.getPageData();
            try {
                String keywords = pd.getString("inputVar");
                if (keywords != null) {
                    String keywords1 = URLDecoder.decode(keywords, "UTF-8");
                    pd.put("keywords", keywords1);
                    page.setPd(pd);
                }
                pd.put("corpId",this.getUser().getCorpId());
                page.setPd(pd);
                List<SysRole> roleList =sysRoleService .getRolelistPage(page);
                tidings.setT(roleList).setPage(page);
                tidings.setStatus(Const.SUCCESS);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return tidings;
        }
                /*
                * 跳转
                * 添加/修改
                * 页面
                *
                * */

                @RequestMapping("/merchant/role/toRoleEdit")
                public ModelAndView toRoleEdit(String roleId) {
                    ModelAndView md = new ModelAndView();

                    try {
                        SysRole sysRole = sysRoleService.getRoleById(roleId);
                        md.addObject("pRole", sysRole);
                        md.addObject("roleId", roleId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    md.addObject("userid", "");

                    md.setViewName("merchant/mcrole/role_edit");
                    return md;
                }
                    /*
                   * 修改
                   * 角色
                    */


                @RequestMapping("/merchant/mcrole/saveUpdateRole")
                @ResponseBody
                public Object updateRole(@ModelAttribute("sysRole") SysRole sysRole) {
                    Tidings<String> tidings = new Tidings<String>();
                    PageData pd=this.getPageData();
                    String  menuIds=pd.getString("rolemenuId");
                    String[] split = menuIds.split(",");//将前台出入menuId字符串，切割为数组
                    try {
                        if (XSSCheckUtil.checkXSS(sysRole.getRoleName())
                                ||             XSSCheckUtil.checkXSS(sysRole.getRoleCode())
                                ||             XSSCheckUtil.checkXSS(sysRole.getRoleName())
                                ||             XSSCheckUtil.checkXSS(sysRole.getSystem())
                                ||             XSSCheckUtil.checkXSS(sysRole.getCorpId())
                                ||             XSSCheckUtil.checkXSS(sysRole.getDescb())
                                ||             XSSCheckUtil.checkXSS(sysRole.getStatus())
                                ||             XSSCheckUtil.checkXSS(sysRole.getCreator())
                                ||             XSSCheckUtil.checkXSS(sysRole.getUpdator()))
                        {
                            tidings.setStatus(Const.ERROR);
                            tidings.setMsg("非法参数！");
                            return tidings;
                        }

                        if ("".equals(sysRole.getRoleId()) || sysRole.getRoleId() == null) {
                            String roleId=UuidUtil.getNumFormatUUID();
                            sysRole.setRoleId(roleId);//角色id
                            sysRole.setRoleCode(UuidUtil.getNumFormatUUID());//角色编号
                            sysRole.setSystem("02");//02-商户端  01-银行端
                            sysRole.setCorpId(this.getUser().getCorpId());//商户id
                            sysRole.setStatus("2");//0-停用 1-启用 2-未审核
                            //sysRole.setOrderNo(2);//0-停用 1-启用 2-未审核
                            sysRole.setCreateDate(new Date());//创建时间
                            sysRole.setCreator(this.getUser().getNickname());//创建人
                            String roleName=sysRoleService.getRoleNameByRoleNameandCorpId(sysRole.getRoleName(),this.getUser().getCorpId());
                            if (StringUtils.isNotBlank(roleName)){
                                tidings.setStatus(Const.ERROR);
                                tidings.setMsg("角色名已存在！");
                                return tidings;
                            }
                                sysRoleService.saveRole(sysRole);
                                if (split.length>0) {
                                    for (String s : split) {
                                        sysRoleMenuService.addRoleMenus(roleId,s);//用户绑定菜单
                                    }
                                }
                                tidings.setStatus(Const.SUCCESS);
                                tidings.setMsg("保存成功！");

                        } else {
                            sysRole.setUpdator(this.getUser().getNickname());//修改人
                            //sysRole.setStatus("2");//0-停用 1-启用 2-未审核
                            //sysRole.setSystem("");//0-商户端  1-银行端
                            //role.setOrderNo();//排序号
                            sysRole.setUpdateDate(new Date());//修改时间
                            sysRoleService.updateRole(sysRole);
                            List<String> menuslist= sysRoleMenuService.getMenusByRoleId(sysRole.getRoleId());//用户已绑定菜单
                            if (menuslist!=null){
                                for (String s : menuslist) {
                                    sysRoleMenuService.deleteRoleMenu(sysRole.getRoleId());//删除已绑定菜单id
                                }
                                if (split.length>0) {
                                    for (String s : split) {
                                        sysRoleMenuService.addRoleMenus(sysRole.getRoleId(),s);//用户绑定菜单
                                    }
                                }
                            }
                            tidings.setStatus(Const.SUCCESS);
                            tidings.setMsg("修改成功！");
                        }
                    } catch (Exception e) {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("保存失败！");
                        e.printStackTrace();
                    }
                    return tidings;
                }

                /*
                * 查询员角色已经绑定菜单
                * */
                @RequestMapping("/merchant/role/getRoleMenuIds")
                @ResponseBody
                public  Object getMenuIds(String roleId){
                    Tidings<Map> tidings=new Tidings<Map>();
                    Map<String,Object> map=new HashMap<String,Object>();
                    try {

                        Set<String> set=new HashSet<>();
                        List<String> list=sysRoleMenuService.getMenusByRoleId(roleId);
                        List<String> menuNamelist=new ArrayList<>();
                        if(list!=null) {
                            for (String s : list) {
                                if(StringUtils.isNotBlank(s)) {
                                    String roleId1 = sysRoleService.getParentRoleIdByRoleid(s);
                                    set.add(roleId1);
                                    String menuName = sysMenuService.getMenuNameByMenuId(s);
                                    menuNamelist.add(menuName);
                                }
                            }
                        }
                        map.put("list",list);
                        map.put("set",set);
                        map.put("menuNamelist",menuNamelist);
                        tidings.setT(map);
                        tidings.setStatus(Const.SUCCESS);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return tidings;
                };

                /**
                 * jiaoseshanchu 删除角色
                 * @param roleId
                 * @return
                 */
                @RequestMapping("/merchant/role/deleteRole")
                @ResponseBody
                public Object deleteSysRole(String roleId) {
                    Tidings<String> tidings = new Tidings<String>();
                    try {
                        String nowCorpId=this.getUser().getCorpId();//当前登录着商户id
                        String  corpId=sysRoleService.getRoleById(roleId).getCorpId();//被删除角色商户id
                        if(StringUtils.equals(nowCorpId,corpId)){
                            SysUser sysUser=sysUserService.getUserByRoleId(roleId);
                            if(StringUtils.equals(sysUser.getCount(),"0")) {
                                sysRoleService.deleteRole(roleId);
                                tidings.setStatus(Const.SUCCESS);
                                tidings.setMsg("删除成功！");
                            }else {
                                tidings.setStatus(Const.ERROR);
                                tidings.setMsg("请先删除角色下绑定用户，在进行此操作！");
                            }
                        }else {
                            tidings.setStatus(Const.ERROR);
                            tidings.setMsg("对不起您没有此操作权限！");
                        }
                    } catch (Exception e) {
                        tidings.setStatus(Const.ERROR);
                        tidings.setMsg("删除失败！");
                        e.printStackTrace();
                    }
                    return tidings;
                }


    /*
*
* 跳转详情
* */
    @RequestMapping("/merchant/role/toRoleDetial")
    @ResponseBody
    public ModelAndView toUserDetail(Page page) {
        ModelAndView md = new ModelAndView();
        md.setViewName("merchant/sys_management/role_manage_details");
        return md;
    }

    @RequestMapping("/merchant/role/RoleDetial")
    @ResponseBody
    public Object userDetail(String userId) {
            Tidings<SysRole> tidings=new Tidings<SysRole>();
        String corpId=this.getUser().getCorpId();
        try {
            SysRole sysRole=sysRoleService.getRoleByCorpIdAndUserId(corpId,userId);
            if(sysRole!=null){
                tidings.setT(sysRole);
                tidings.setStatus(Const.SUCCESS);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tidings;
    }

}
